<template>
  <!--私密文章密码对话框-->
  <el-dialog title="请输入受保护文章密码" width="30%" v-model.sync="blogPasswordDialogVisible"
             :lock-scroll="false" :before-close="blogPasswordDialogClosed">
    <!--内容主体-->
    <el-form :model="blogPasswordForm" :rules="formRules" ref="formRef" label-width="80px">
      <el-form-item label="密码" prop="password">
        <el-input v-model="blogPasswordForm.password"></el-input>
      </el-form-item>
    </el-form>
    <!--底部-->
    <template #footer>
          <span>
			<el-button @click="blogPasswordDialogClosed">取 消</el-button>
			<el-button type="primary" @click="submitBlogPassword">确 定</el-button>
		</span>
    </template>
  </el-dialog>
</template>

<script setup>
import {SET_BLOG_PASSWORD_DIALOG_VISIBLE} from "@/store/mutations-types";
import {checkBlogPassword} from "@/api/blog";
import {useState} from "@/util/useState";
import {getCurrentInstance, reactive, ref} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";


const {blogPasswordDialogVisible, blogPasswordForm} = useState(['blogPasswordDialogVisible', 'blogPasswordForm'])
const formRules = reactive({
  password: [{required: true, message: '请输入密码', trigger: 'change'}]
})

const formRef = ref(null)
const store = useStore()

function blogPasswordDialogClosed() {
  formRef.value.resetFields()
  store.commit(SET_BLOG_PASSWORD_DIALOG_VISIBLE, false)
}

const {proxy} = getCurrentInstance()
const router = useRouter()

function submitBlogPassword() {
  formRef.value.validate(valid => {
    if (valid) {
      checkBlogPassword(blogPasswordForm.value).then(res => {
        if (res.code === 200) {
          proxy.msgSuccess(res.msg)
          window.localStorage.setItem(`blog${blogPasswordForm.value.blogId}`, res.data)
          router.push(`/blog/${blogPasswordForm.value.blogId}`)
          blogPasswordDialogClosed()
        } else {
          proxy.msgError(res.msg)
        }
      }).catch(() => {
        proxy.msgError("请求失败")
      })
    }
  })
}

</script>

<style scoped>

</style>
